<template>
  <div style="width:100%;">
    <div class="query-form">
      <el-form ref="queryForm" :inline="true" :model="data_query_form.data">
        <el-form-item label="产品编码：" prop="productCode">
          <el-input v-model="data_query_form.data.productCode" type="text" placeholder="产品编码" />
        </el-form-item>
        <el-form-item label="产品名称(中)：" prop="productName">
          <el-input v-model="data_query_form.data.productName" type="text" placeholder="产品名称(中)" />
        </el-form-item>
        <el-form-item label="产品线：" prop="productLineCode">
          <el-select v-model="data_query_form.data.productLineCode" placeholder="产品线">
            <el-option
              v-for="item in data_query_form.prodLineOps"
              :key="item.productLineCode"
              :label="item.productLineName"
              :value="item.productLineCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="queryFormReset">重置</el-button>
          <el-button type="primary" @click="queryFormQuery">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="product-list">
      <el-editable
        ref="productsList"
        v-loading="productTableLoading"
        height="400"
        :need-pagination="true"
        :columns="data_product_list.columns[type]"
        :payload="data_product_list.data"
        :static-store="store"
        @reload="reloadData"
        @select="curSelect"
        @select-all="onSelectAll"
      />
    </div>
  </div>
</template>

<script>
import ElEditable from '@components/el-editable';
import { defaultListColumns, surgeryListColumns, consumeListColumns } from './product.const.js';
import { orderPurchaseProductPageList } from '@api/m_mall_web_v1.js';
import { isObject, compact } from 'lodash';
export default {
  name: 'ProductAddDialogProductListComponent',
  components: { ElEditable },
  props: {
    type: {
      type: String,
      default: 'default'
    },
    query: {
      type: Object,
      default: function() {
        return {};
      }
    },
    fetcher: {
      type: Function,
      default: function() {}
    },
    store: null
  },
  data() {
    return {
      data_query_form: {
        prodLineOps: [],
        data: {
          productCode: '',
          productName: '',
          productLineCode: ''
        }
      },
      data_product_list: {
        storageProducts: [],
        data: {},
        columns: {
          default: defaultListColumns,
          surgery: surgeryListColumns,
          consume: consumeListColumns
        }
      },
      page: 1,
      selectedProducts: [],
      productTableLoading: false
    };
  },
  created() {
    this.setInitDataAndGetFirstData();
  },
  methods: {
    // 初始化搜索条件并请求初始化接口数据
    setInitDataAndGetFirstData() {
      // 这里唯一要做的数据初始化，是设置产品线的数据。
      this.data_query_form.prodLineOps.push({
        productLineCode: this.query.formData.contractVo.productLineCode,
        productLineName: this.query.formData.contractVo.productLineName
      });
      // 写死产品线搜索条件的值
      //
      this.data_query_form.data.productLineCode = this.query.formData.contractVo.productLineCode;
      this.reloadData({ number: 1, size: 20 });
    },
    reloadData(pager) {
      // 切换分页时，存储数据
      this.productTableLoading = true;
      this.page = pager.number;
      this.fetcher({
        url: orderPurchaseProductPageList,
        method: 'post',
        data: {
          busModel: this.query.formData.busModel || this.query.formData.contractVo.businessModelCode,
          marketCode: this.query.formData.contractVo.marketCode,
          page: pager.number,
          pageSize: pager.size,
          productCode: this.data_query_form.data.productCode,
          productLineCode: this.data_query_form.data.productLineCode,
          productName: this.data_query_form.data.productName,
          vendorNum: this.query.formData.supplierVo.vendorCode,
          ddbm: this.query.orderTypeDDBM
        }
      })
        .then(res => {
          let result = isObject(res.data.payload) ? res.data.payload : [];
          this.data_product_list.data = result;
          if (this.data_product_list.storageProducts.length > 0) {
            this.reActiveListRows();
          }
        })
        .finally(() => {
          this.productTableLoading = false;
        });
    },
    reActiveListRows() {
      let curPageRow = this.data_product_list.storageProducts;
      if (curPageRow && curPageRow.length > 0) {
        curPageRow.forEach(item => {
          let findItem = this.data_product_list.data.content.find(it => {
            return it.productCode === item.productCode;
          });
          if (findItem) {
            this.$nextTick(() => {
              this.$refs.productsList.$refs.table.toggleRowSelection(findItem, true);
            });
          }
        });
      }
    },
    queryFormReset() {
      this.$refs['queryForm'].resetFields();
      this.queryFormQuery();
    },
    queryFormQuery() {
      this.reloadData({ number: 1, size: 20 });
    },
    deDuplication(curSelectedProducts) {
      this.data_product_list.storageProducts = this.data_product_list.storageProducts.concat(curSelectedProducts);
      console.log(this.uniqueDoubleCycle(this.data_product_list.storageProducts, 'productCode'));
      this.data_product_list.storageProducts = this.uniqueDoubleCycle(
        this.data_product_list.storageProducts,
        'productCode'
      );
      return this.data_product_list.storageProducts;
    },
    onSelectAll(selection) {
      // 如果有数据，说明是全选选中状态，那么把所有的数据放入storageProducts并去重
      if (selection.length) {
        this.data_product_list.storageProducts = this.deDuplication(
          this.data_product_list.storageProducts.concat(this.data_product_list.data.content)
        );
      } else {
        // 如果没数据，就把当前页this.data_product_list.data的数据从storageProducts挨个删除
        // 即从存储的产品池中，删除当前已取消的产品（因为是全选操作，所以已取消的产品，即当页所有产品）
        this.data_product_list.storageProducts.forEach((item, index) => {
          let findItem = this.data_product_list.data.content.find(it => {
            return it.productCode === item.productCode;
          });
          if (findItem) {
            // 猜猜这里为啥用undefined占位？
            this.data_product_list.storageProducts.splice(index, 1, undefined);
          }
        });
      }
      // 数组去空
      this.data_product_list.storageProducts = compact(this.data_product_list.storageProducts);
      this.$emit('selectionChange', this.data_product_list.storageProducts);
    },
    curSelect(selection, row) {
      // 判断当前是选中还是取消,true是选中，false是取消
      let flag;
      flag =
        selection.findIndex(item => {
          return item.productCode === row.productCode;
        }) !== -1;
      // 是否存在于相应的数据中
      let storageIdx = this.data_product_list.storageProducts.findIndex(item => {
        return item.productCode === row.productCode;
      });
      if (flag) {
        // 如果是增加，就一股脑把当前所有选中的selection都放进storageProducts，然后再去重
        this.data_product_list.storageProducts = this.deDuplication(
          this.data_product_list.storageProducts.concat(selection)
        );
      } else {
        // 如果是减少，那么直接删除在storageProducts中对应下标的数据
        this.data_product_list.storageProducts.splice(storageIdx, 1);
      }
      this.$emit('selectionChange', this.data_product_list.storageProducts);
    },
    // 去重算法
    uniqueDoubleCycle(array, key) {
      let newArr = [];
      let len = array.length;
      let isRepeat;

      for (let i = 0; i < len; i++) {
        // 第一次循环
        isRepeat = false;
        for (let j = i + 1; j < len; j++) {
          // 第二次循环
          if (array[i][key] === array[j][key]) {
            isRepeat = true;
            break;
          }
        }
        if (!isRepeat) {
          newArr.push(array[i]);
        }
      }
      return newArr;
    }
  }
};
</script>

<style lang="less" scoped>
.product-list {
  margin-top: 60px;
  display: flex;
  flex: 1;
  .pagination {
    text-align: right;
    margin-top: 20px;
  }
}
</style>
